<template>
	<!-- 搜索框 -->
    <el-card>
        <el-form :model="searchFeedBackForm"  inline>
            <el-form-item label="工作站名称" prop="workstationNameQuery">
                <el-input v-model="searchFeedBackForm.workstationNameQuery" placeholder="请输入工作站名称" />
            </el-form-item>
            <el-form-item label="生产工单编号" prop="workorderCodeQuery">
                <el-input v-model="searchFeedBackForm.workorderCodeQuery" placeholder="请输入生产工单编号" />
            </el-form-item>
            <el-form-item label="产品物料编码" prop="itemCodeQuery">
                <el-input v-model="searchFeedBackForm.itemCodeQuery" placeholder="请输入产品物料编码" />
            </el-form-item>
            <el-form-item label="产品物料名称" prop="itemNameQuery">
                <el-input v-model="searchFeedBackForm.itemNameQuery" placeholder="请输入产品物料名称" />
            </el-form-item>
            <el-form-item label="报工人名称" prop="userNameQuery">
                <el-input v-model="searchFeedBackForm.userNameQuery" placeholder="请输入报工人名称" />
            </el-form-item>
            <el-form-item label="记录人" prop="recordUserQuery">
                <el-input v-model="searchFeedBackForm.recordUserQuery" placeholder="请输入记录人" />
            </el-form-item>
            <el-form-item label="状态" prop="statusQuery">
                <el-select v-model="searchFeedBackForm.statusQuery" placeholder="请选择状态" style="width: 150px;">
                    <el-option label="待审核" value="PREPARE" />
                    <el-option label="已审核" value="AUDIT" />
                    <el-option label="已取消" value="CANCEL" />
                </el-select>
            </el-form-item>
            <el-form-item label="报工类型" prop="feedbackTypeQuery" >
                <el-select v-model="searchFeedBackForm.feedbackTypeQuery" placeholder="请选择报工类型"  style="width: 150px;">
                    <el-option label="报工" value="FEEDBACK" />
                    <el-option label="审核" value="AUDIT" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchFeedBackList">搜索</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
		<el-form>
			<el-button size="default" type="success" @click="handleAddFeedBack">新增生产报工</el-button>
			<el-button size="default" type="danger" @click="handleBatchDelete">删除生产报工</el-button>
			<el-button size="default" type="info" @click="handleexportFeedBackExcel">导出报工</el-button>

		</el-form>
    </el-card>
	
	<!-- 生产报工信息 table -->
	<el-card>
        	<el-table :data="feedbackList" style="width: 100%" ref="feedbackTableRef" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
            <el-table-column prop="feedbackCode" label="报工单号"/>
            <el-table-column prop="feedbackType" label="报工类型"/>
            <el-table-column prop="workstationId" label="工作站编号"/>
            <el-table-column prop="workorderCode" label="工单编码"/>
            <el-table-column prop="workorderCode" label="工单编码"/>
            <el-table-column prop="itemCode" label="产品物料编码"/>
            <el-table-column prop="itemName" label="产品物料名称"/>
            <el-table-column prop="unitName" label="单位"/>
            <el-table-column prop="quantityFeedback" label="单位"/>
            <el-table-column prop="quantityQualified" label="单位"/>
            <el-table-column prop="quantityUnqualified" label="单位"/>
            <el-table-column label="操作">
              <template #default="scope" style="width: 400px;" >
                <el-button size="default" type="info" @click="handleEditFeedBack(scope.row)">修改</el-button>
				
				<el-button size="default" type="danger" @click="handlefeebackDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
	</el-card>
	
	
	<!-- 分页信息 -->
	<div class="demo-pagination-block">
	    <el-pagination
	      v-model:current-page="pagination.currentPage"
	      v-model:page-size="pagination.pageSize4"
	      :page-sizes="[10, 20, 30, 50]"
	      :size="size"
	      :disabled="disabled"
	      :background="background"
	      layout="total, sizes, prev, pager, next, jumper"
	      :total="pagination.total"
	      @size-change="handleSizeChange"
	      @current-change="handleCurrentChange"
	    />
	</div>
	
	
	<!-- dialog添加/编辑弹窗 -->
	<el-dialog
	    v-model="dialogFeedBackVisible"
	    :title="isFeedBackEditMode?'编辑':'新增'"
	    width="1200"
	    :before-close="handleClose"
	  >
		<el-form :inline="true" :model="dialogFeedBackInfo" class="demo-form-inline">
			<el-form-item label="报工类型">
				<el-select v-model="dialogFeedBackInfo.feedbackType" placeholder="请选择报工类型" style="width: 100px">
					<el-option label="生产报工" value="PRODUCTION"></el-option>
					<el-option label="白件报工" value="WHITE_PART"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="报工单号">
				<el-input v-model="dialogFeedBackInfo.feedbackCode" placeholder="请输入报工单号" style="width: 150px;"></el-input>
			</el-form-item>
			<el-form-item label="生产工单">
				<el-input 
					v-model="dialogFeedBackInfo.workorderCode" 
					placeholder="请输入生产工单编号" 
					style="width: 200px;">
					<template #suffix>
						<el-icon @click="openWorkorderModal" style="cursor: pointer;">
							<Search />
						</el-icon>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="工作id">
				<el-input v-model="dialogFeedBackInfo.workstationId" placeholder="请输入工作站名称" style="width: 150px;"></el-input>
			</el-form-item>
			<el-form-item label="产品编号">
				<el-input v-model="dialogFeedBackInfo.itemCode" placeholder="请输入产品编号"></el-input>
			</el-form-item>
			<el-form-item label="产品名称">
				<el-input v-model="dialogFeedBackInfo.itemName" placeholder="请输入产品名称"></el-input>
			</el-form-item>
			<el-form-item label="单位">
				<el-input v-model="dialogFeedBackInfo.unitName" placeholder="请输入单位"></el-input>
			</el-form-item>
			<el-form-item label="规格型号">
				<el-input v-model="dialogFeedBackInfo.specification" placeholder="请输入规格型号"></el-input>
			</el-form-item>
			<el-form-item label="报工数量">
				<el-input-number v-model="dialogFeedBackInfo.quantityFeedback"  placeholder="请输入报工数量"></el-input-number>
			</el-form-item>
			<el-form-item label="合格数量">
				<el-input-number v-model="dialogFeedBackInfo.quantityQualified" placeholder="请输入合格数量"></el-input-number>
			</el-form-item>
			<el-form-item label="不良数量">
				<el-input-number v-model="dialogFeedBackInfo.quantityUnqualified" placeholder="请输入不良数量"></el-input-number>
			</el-form-item>
			<el-form-item label="报工人">
				<el-input v-model="dialogFeedBackInfo.userName" placeholder="请输入报工人用户名"></el-input>
			</el-form-item>
			<el-form-item label="报工人姓名">
				<el-input
					v-model="dialogFeedBackInfo.nickName" 
					placeholder="请输入报工人姓名" 
					style="width: 200px;">
					<template #suffix>
						<el-icon @click="openUserModal('feedback')" style="cursor: pointer;">
							<Search />
						</el-icon>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="报工时间">
				<el-date-picker v-model="dialogFeedBackInfo.feedbackTime" type="datetime" placeholder="请选择报工时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
			</el-form-item>	
			<el-form-item label="审核人">
				<el-input v-model="dialogFeedBackInfo.recordUser" placeholder="请输入审核人用户名"></el-input>
			</el-form-item>
			<el-form-item label="审核人姓名">
				<!-- ToDo -->
				<el-input
					v-model="dialogFeedBackInfo.recordNick" 
					placeholder="请输入审核人姓名" 
					style="width: 200px;">
					<template #suffix>
						<el-icon @click="openUserModal('record')" style="cursor: pointer;">
							<Search />
						</el-icon>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="状态">
				<el-select v-model="dialogFeedBackInfo.status" placeholder="请选择状态" style="width: 100px">
					<el-option label="草稿" value="PREPARE"></el-option>
					<el-option label="审批中" value="APPROVING"></el-option>
					<el-option label="已审核" value="APPROVED"></el-option>
					<el-option label="已执行" value="EXECUTED"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="备注">
				<el-input v-model="dialogFeedBackInfo.remark" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
			</el-form-item>
		</el-form>
		
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="dialogFeedBackVisible = false">取消</el-button>
	        <el-button type="primary" @click="handleAddOrEditFeedBack">
	          确认
	        </el-button>
	      </div>
	    </template>
	  </el-dialog>
	  
	  
	
	<!-- 获取生产任务列表 -->
	<el-dialog v-model="dialogProscheduleFormVisible" title="生产工单" width="1200">
	   <el-table :data="productionTaskList" style="width: 100%" @current-change="handleFeedBackCurrentChange" highlight-current-row>
	     <el-table-column type="index"  width="55" />
	     <el-table-column property="taskCode" label="任务编号" width="120"/>
	     <el-table-column property="taskName" label="任务名称" width="120"/>
	     <el-table-column property="workstationId" label="工作站编号" width="120"/>
	     <!--<el-table-column property="workstation_name" label="工作站名称" width="120"/>-->
	     <el-table-column property="processId" label="工序编号" width="120"/>
	     <el-table-column label="物资编码" width="120"/>
	     <el-table-column property="plannedQuantity" label="排产数量" width="120"/>
	     <el-table-column property="completedQuantity" label="已生产数量" width="120"/>
	     <el-table-column property="startTime" label="开始生产时间" width="120"/>
	     <el-table-column property="durationHours" label="生产时长" width="120"/>
	     <el-table-column property="endTime" label="预计完成时间" width="120"/>
	     <el-table-column property="colorCode" label="显示颜色" width="120"/>
	   </el-table>

	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="dialogProscheduleFormVisible = false">Cancel</el-button>
	        <el-button type="primary" @click="dialogProscheduleFormVisible = false">
	          Confirm
	        </el-button>
	      </div>
	    </template>
	  </el-dialog>  
	  
	  
	<!-- 获取员工信息 -->
	<el-dialog v-model="dialogUserFormVisible" title="生产工单" width="1200">
	    <el-table
	      :data="UserList"
	      border
	      stripe
	      @current-change="handleUserChange" 
		  highlight-current-row
	    >
	      <el-table-column prop="id" label="ID" width="80" />
	      <el-table-column prop="username" label="用户名" />
	      <el-table-column prop="email" label="邮箱" />
	      <el-table-column prop="role" label="角色" >
	      </el-table-column>
	      <el-table-column prop="createdTime" label="创建时间" width="180" />
	      <el-table-column prop="status" label="状态" width="80">
	        <template #default="scope">
	          <el-tag :type="scope.row.status == '1' ? 'success' : 'danger'">
	            {{ scope.row.status == '1' ? '启用' : '禁用' }}
	          </el-tag>
	        </template>
	      </el-table-column>
	    </el-table>
	
	    <template #footer>
	      <div class="dialog-footer">
	        <el-button @click="dialogUserFormVisible = false">Cancel</el-button>
	        <el-button type="primary" @click="dialogUserFormVisible = false">
	          Confirm
	        </el-button>
	      </div>
	    </template>
	  </el-dialog>  
	
	
	
</template>

<script setup>
	import { ref,onMounted } from 'vue';
	import { Search } from '@element-plus/icons-vue';
	import { getFeedbackList,exportFeedBack,getFeedbackById,addFeedback,updateFeedback,deleteFeedback,batchDeleteFeedback} from '@/api/feedback.js';
	import { getProductionTaskPageList } from '@/api/productionTask';
	import { ElMessage, ElMessageBox } from 'element-plus';
	import { getUserList } from '@/api/user';
    
    // 搜索表单
    const searchFeedBackForm = ref({
        workstationNameQuery: '',
        workorderCodeQuery: '',
        itemCodeQuery: '',
        itemNameQuery: '',
        userNameQuery: '',
        recordUserQuery: '',
        statusQuery: '',
        feedbackTypeQuery: '',
    })

    const feedbackList = ref([])
    const selectedFeedbacks = ref([]) // 存储选中的数据
    const feedbackTableRef = ref(null) // 表格引用

	//分页信息
    const pagination = ref({
        currentPage: 1,
        pageSize: 10,
        total: 0
    });
	
	// 改变分页大小
	const handleSizeChange =(newSize)=>{
		pagination.value.pageSize = newSize;
		searchFeedBackList();
	}
	
	// 改变当前页数
	const handleCurrentChange =(newPage)=>{
		pagination.value.currentPage = newPage;
		searchFeedBackList();
	}
	
	// 重置搜索条件
	const reset = () => {
		searchFeedBackForm.value = {
			workstationNameQuery: '',
			workorderCodeQuery: '',
			itemCodeQuery: '',
			itemNameQuery: '',
			userNameQuery: '',
			recordUserQuery: '',
			statusQuery: '',
			feedbackTypeQuery: '',
		}
		// 重置后重新搜索
		searchFeedBackList();
	}
	
	// 获取对应的生产报式列表
	const searchFeedBackList =()=>{
		const params = ({
			page: pagination.value.currentPage,
			pageSize: pagination.value.pageSize,
            ...searchFeedBackForm.value  
		})
		console.log(params)
		getFeedbackList(params).then(res=>{
			console.log(res.data.list);
			pagination.value.total = res.data.total;
			feedbackList.value = res.data.list;
		})
	}
	
	// ======================= 弹窗设计 =========================
	const dialogFeedBackVisible = ref(false);
	
	// 重置表单数据
	const resetDialogForm = () => {
		dialogFeedBackInfo.value = {
			recordId: null,
			feedbackCode: '',
			feedbackType: 'PRODUCTION',
			workstationId: null,
			workstationName: '',
			workOrderId: null,
			workorderCode: '',
			taskId: null,
			taskCode: '',
			itemCode: '',
			itemName: '',
			specification: '',
			unitName: '',
			quantityFeedback: 0,
			quantityQualified: 0,
			quantityUnqualified: 0,
			userName: '',
			nickName: '',
			feedbackTime: '',
			recordUser: '',
			recordNick: '',
			status: 'PREPARE',
			remark: '',
			createTime: '',
			updateTime: '',
			workstationNameQuery: null,
			workorderCodeQuery: null,
			itemCodeQuery: null,
			itemNameQuery: null,
			userNameQuery: null,
			recordUserQuery: null,
			statusQuery: null,
			feedbackTypeQuery: null
		};
	}

  const handleexportFeedBackExcel = () =>{
		exportFeedBack().then(response => {
		const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		link.download = '生产报工表.xlsx';
		link.click();
		window.URL.revokeObjectURL(url);
	})
  }
	
	//添加按钮
	const handleAddFeedBack = () => {
    isFeedBackEditMode.value = false;
		resetDialogForm();
		dialogFeedBackVisible.value = true;
	}
	
	// 编辑按钮
	const handleEditFeedBack = (row) => {
    resetDialogForm();
    isFeedBackEditMode.value = true;

    console.log(row)
		// 根据选择中的行获取对应的信息
		getFeedbackById(row.recordId).then(res=>{
			dialogFeedBackInfo.value = res.data
		})
		dialogFeedBackVisible.value = true;
	}
	
	// 弹窗数据绑定
	const dialogFeedBackInfo = ref({
		recordId: null,
		feedbackCode: '',
		feedbackType: 'PRODUCTION',
		workstationId: null,
		workstationName: '',
		workOrderId: null,
		workorderCode: '',
		taskId: null,
		taskCode: '',
		itemCode: '',
		itemName: '',
		specification: '',
		unitName: '',
		quantityFeedback: 0,
		quantityQualified: 0,
		quantityUnqualified: 0,
		userName: '',
		nickName: '',
		feedbackTime: '',
		recordUser: '',
		recordNick: '',
		status: 'PREPARE',
		remark: '',
		createTime: '',
		updateTime: '',
		// 查询条件字段（用于搜索）
		workstationNameQuery: null,
		workorderCodeQuery: null,
		itemCodeQuery: null,
		itemNameQuery: null,
		userNameQuery: null,
		recordUserQuery: null,
		statusQuery: null,
		feedbackTypeQuery: null
	})
	

	// 删除按钮
	const handlefeebackDelete = (row) => {
		deleteFeedback(row.recordId).then(res=>{
			if(res.code == 200){
				ElMessage.success('删除成功')
				searchFeedBackList();
			}else{
				ElMessage.error('删除失败')
			}
		})
	}

	// 处理表格选择变化
	const handleSelectionChange = (selection) => {
		selectedFeedbacks.value = selection;
	}

	// 批量删除功能
	const handleBatchDelete = async () => {
		// 检查是否有选中的数据
		if (selectedFeedbacks.value.length === 0) {
			ElMessage.warning('请先选择要删除的数据');
			return;
		}

		try {
			// 弹出确认对话框
			await ElMessageBox.confirm(
				`确定要删除选中的 ${selectedFeedbacks.value.length} 条数据吗？`,
				'删除确认',
				{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			);

			// 提取选中数据的recordId
			const ids = selectedFeedbacks.value.map(item => item.recordId);
			
			// 调用批量删除接口
			const res = await batchDeleteFeedback(ids);
			
			if (res.code === 200) {
				ElMessage.success(`成功删除 ${selectedFeedbacks.value.length} 条数据`);
				// 清空选中状态
				selectedFeedbacks.value = [];
				// 刷新列表
				searchFeedBackList();
			} else {
				ElMessage.error(res.message || '删除失败');
			}
		} catch (error) {
			// 用户取消操作或其他错误
			if (error !== 'cancel') {
				ElMessage.error('删除操作失败');
			}
		}
	}
	
	// ===================================工单信息====================================
	// 添加工单的弹窗
	const dialogProscheduleFormVisible = ref(false);
	
	const productionTaskList = ref([]);
	
	// 分页数据
		const Proschedulepagination = ref({
		  currentPage: 1,
		  pageSize: 10,
		  total: 0
		});
	
		// 改变分页大小
		const handleProscheduleSizeChange = (newSize) =>{
			Proschedulepagination.value.pageSize = newSize;
			Proschedulepagination.value.currentPage = 1;
			handleSearchWorkorder();
		}
	
		// 改变当前页码
		const handleProscheduleCurrentChange =(newPage)=>{
			Proschedulepagination.value.currentPage = newPage;
			handleSearchWorkorder();
		}

  //  选择对应的生产任务
  const handleFeedBackCurrentChange =(currentRow)=>{
      console.log('选中的生产任务数据:', currentRow)
      // 将选中的生产任务数据填入到 dialogFeedBackInfo 中
      if (currentRow) {
          dialogFeedBackInfo.value.taskCode = currentRow.taskCode; // PT20250925004
          dialogFeedBackInfo.value.taskId = currentRow.id; // 4
          dialogFeedBackInfo.value.workstationId = currentRow.workstationId; // 6
          dialogFeedBackInfo.value.workorderCode = currentRow.taskCode; // 使用任务编号作为工单编号
          dialogFeedBackInfo.value.processId = currentRow.processId; // 4
          dialogFeedBackInfo.value.workOrderId = currentRow.productionOrderId; // 8
          dialogFeedBackInfo.value.itemCode = currentRow.materialCode; // MAT008 物料编码
          dialogFeedBackInfo.value.itemName = currentRow.taskName; // 华为PCB-喷漆工序
          dialogFeedBackInfo.value.plannedQuantity = currentRow.plannedQuantity; // 300
          dialogFeedBackInfo.value.completedQuantity = currentRow.completedQuantity; // 0
      }
  }


	//   获取对应的生产任务
	const openWorkorderModal =()=>{
		dialogProscheduleFormVisible.value = true;
		getProductionTaskPageList(Proschedulepagination.value.currentPage,Proschedulepagination.value.pageSize).then(res=>{
			console.log(res.data.list)
			productionTaskList.value = res.data.list;
		})
	}

  const isFeedBackEditMode = ref(false);
	
	//	编辑/添加报工
	const handleAddOrEditFeedBack =()=>{
		const apiFn = isFeedBackEditMode.value ? updateFeedback : addFeedback;
		const successMessage = isFeedBackEditMode.value ? '更新成功' : '添加成功';
		const errorMessage = isFeedBackEditMode.value ? '更新失败' : '添加失败';

    dialogProscheduleFormVisible.value = false;
		
		apiFn(dialogFeedBackInfo.value).then(res=>{
			if (res.code == 200) {
			  ElMessage.success(successMessage);
			  resetDialogForm();
			  searchFeedBackList();
			} else {
			  ElMessage.error(errorMessage);
			}
		})
	}
	
	
	
	// =========================获取用户信息  TODO
	// 用于标识当前选择的用户类型
	const currentUserType = ref('');
	// 用户弹窗开关
	const dialogUserFormVisible = ref(false);
	
	//用户信息
	const UserList = ref([]);
	
	const Userpagination = ref({
	  currentPage: 1,
	  pageSize: 10,
	  total: 0
	});
	
	// 改变分页大小
	const handleUserSizeChange = (newSize) =>{
		Userpagination.value.pageSize = newSize;
		Userpagination.value.currentPage = 1;
		handleSearchWorkorder();
	}
		
	// 改变当前页码
	const handleUserCurrentChange =(newPage)=>{
		Userpagination.value.currentPage = newPage;
		handleSearchWorkorder();
	}
	
	// 查询用户列表
	const handleSearchWorkorder =()=>{
		const params = {
			pageNum: Userpagination.value.currentPage,
			size: Userpagination.value.pageSize,
			...null
		 };
		getUserList(params).then(res=>{
			console.log(res.data);
			UserList.value = res.data;
		})
	}
	
	
	//  用户搜索按钮绑定事件
	const openUserModal =(type)=>{
		currentUserType.value = type;
		dialogUserFormVisible.value = true;
		handleSearchWorkorder();
	}
	
	// 选择数据回填  
	const handleUserChange =(currentRow)=>{
		// current-change 在取消选择或数据刷新时会传 null
		if (!currentRow) {
			return;
		}

		const username = currentRow.username;
		const displayName = currentRow.nickname || currentRow.nickName || currentRow.username;

		if (currentUserType.value === 'feedback') {
			// 回填报工人信息
			dialogFeedBackInfo.value.userName = username;
			dialogFeedBackInfo.value.nickName = displayName;
		} else if (currentUserType.value === 'record') {
			// 回填审核人信息
			dialogFeedBackInfo.value.recordUser = username;
			dialogFeedBackInfo.value.recordNick = displayName;
		}
	
		dialogUserFormVisible.value = false;
	}
	
	
	onMounted(()=>{
		searchFeedBackList();
	})
</script>

<style scoped>

</style>